var fs = require('fs');
var data = '';
var rs = fs.createReadStream('./test.txt');
var ws2 = fs.createWriteStream('./output.txt');
rs.setEncoding('utf-8');
rs.on('data', function (chunk) {
    data += chunk;
});
rs.on('end', function () {
    console.log(data);
    rs.close();
    write();
});
rs.on('error', function (err) {
    throw new Error(err.stack);
});
// 写入
function write() {
    var ws = fs.createWriteStream('./test.txt');
    console.log(data);
    ws.write(data, 'UTF8');
    ws.end();
    ws.on('finish', function () {
        console.log('write complete!');
    });
    ws.on('error', function (err) {
        throw new Error(err.stack);
    });
};

// 管道流
rs.pipe(ws2);

// 链式流
// 链式是通过连接输出流到另外一个流并创建多个对个流操作链的机制。链式流一般用于管道操作。
var zlib = require('zlib');

// 压缩 input.txt 文件为 input.txt.gz
fs.createReadStream('./input.txt').pipe(zlib.createGzip()).pipe(fs.createWriteStream('./input.txt.gz'));
console.log('文件压缩完成！');
//解压缩
fs.createReadStream('./input.txt.gz').pipe(zlib.createGunzip()).pipe(fs.createWriteStream('input.txt'));
console.log('文件解压完成！')